<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="profile-header">
          <h2>个人信息</h2>
          <el-button type="primary" @click="startEditing" v-if="!isEditing">编辑</el-button>
          <div v-else>
            <el-button type="success" @click="saveProfile">保存</el-button>
            <el-button @click="cancelEditing">取消</el-button>
          </div>
        </div>
      </template>
      
      <div class="profile-content">
        <div class="avatar-section">
          <el-avatar :size="100" :src="avatarUrl"></el-avatar>
          <el-upload
            v-if="isEditing"
            class="avatar-uploader"
            action="/api/file/avatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
        
        <div class="info-section">
          <el-form :model="userInfo" label-width="80px" :disabled="!isEditing">
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色">
              <el-input v-model="userRoleText" disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="userInfo.realName"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="userInfo.phone"></el-input>
            </el-form-item>
          </el-form>
          
          <el-divider>密码管理</el-divider>
          
          <el-button type="warning" @click="showPasswordDialog">修改密码</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="30%">
      <el-form :model="passwordForm" label-width="100px" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue';
import { useUserStore } from '../../store/user';
import { getUserInfo, updateUserInfo, changePassword as apiChangePassword } from '../../api/user';
import { ElMessage } from 'element-plus';

export default {
  name: 'StudentProfile',
  setup() {
    const userStore = useUserStore();
    const passwordFormRef = ref(null);
    const userInfo = ref({
      id: '',
      username: '',
      role: '',
      realName: '',
      email: '',
      phone: '',
      avatar: ''
    });
    const originalUserInfo = ref({});
    const isEditing = ref(false);
    const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
    const passwordDialogVisible = ref(false);
    
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { 
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          }, 
          trigger: 'blur' 
        }
      ]
    };
    
    const userRoleText = computed(() => {
      return userInfo.value.role === 'student' ? '学生' : '教师';
    });
    
    // 添加计算属性处理头像URL
    const avatarUrl = computed(() => {
      if (!userInfo.value.avatar) {
        console.log('使用默认头像');
        return defaultAvatar;
      }
      
      // 如果已经是完整URL，直接返回
      if (userInfo.value.avatar.startsWith('http')) {
        console.log('使用完整URL头像:', userInfo.value.avatar);
        return userInfo.value.avatar;
      }
      
      // 前端开发环境修复：如果是以/avatar开头的路径，需要加上后端基础URL
      if (userInfo.value.avatar.startsWith('/avatar')) {
        const resourceUrl = 'http://localhost:8080';
        console.log('使用后端资源URL:', resourceUrl + userInfo.value.avatar);
        return resourceUrl + userInfo.value.avatar;
      }
      
      // 否则使用默认头像
      console.log('无法识别的头像路径，使用默认头像');
      return defaultAvatar;
    });
    
    onMounted(() => {
      fetchUserInfo();
    });
    
    const fetchUserInfo = async () => {
      try {
        // 先从store获取用户ID
        const userId = userStore.userId;
        if (!userId) {
          ElMessage.error('未获取到用户信息，请重新登录');
          return;
        }
        
        // 从后端获取最新用户信息
        const response = await getUserInfo(userId);
        if (response.code === 200) {
          userInfo.value = response.data;
          console.log('获取到的用户信息:', userInfo.value);
          console.log('头像路径:', userInfo.value.avatar);
          originalUserInfo.value = JSON.parse(JSON.stringify(userInfo.value));
        } else {
          ElMessage.error(response.message || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败');
      }
    };
    
    const startEditing = () => {
      isEditing.value = true;
    };
    
    const cancelEditing = () => {
      userInfo.value = JSON.parse(JSON.stringify(originalUserInfo.value));
      isEditing.value = false;
    };
    
    const saveProfile = async () => {
      try {
        // 调用后端API更新用户信息
        const response = await updateUserInfo(userInfo.value);
        if (response.code === 200) {
          // 更新store中的用户信息
          userStore.userInfo = { ...userInfo.value };
          
          // 确保触发store中getter的重新计算
          setTimeout(() => {
            console.log('保存后重新获取的头像URL:', userStore.avatar);
          }, 50);
          
          localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
          originalUserInfo.value = JSON.parse(JSON.stringify(userInfo.value));
          isEditing.value = false;
          ElMessage.success('个人信息更新成功');
        } else {
          ElMessage.error(response.message || '更新个人信息失败');
        }
      } catch (error) {
        console.error('更新个人信息失败:', error);
        ElMessage.error('更新个人信息失败');
      }
    };
    
    const handleAvatarSuccess = async (response) => {
      console.log('头像上传响应:', response);
      // 确保响应是成功的
      if (response && response.code === 200) {
        // 从message字段获取路径，因为后端将路径放在了message字段而非data字段
        let avatarPath = response.message;
        console.log('原始头像路径:', avatarPath);
        
        // 确保图片路径正确
        if (avatarPath && !avatarPath.startsWith('http') && !avatarPath.startsWith('/')) {
          avatarPath = '/' + avatarPath;
        }
        
        console.log('设置的头像路径:', avatarPath);
        
        // 准备更新的用户信息对象
        const updateData = {
          ...userInfo.value,
          avatar: avatarPath
        };
        
        console.log('准备更新的用户信息:', updateData);
        
        try {
          // 调用API更新用户信息
          const updateResponse = await updateUserInfo(updateData);
          console.log('更新用户信息响应:', updateResponse);
          
          if (updateResponse && updateResponse.code === 200) {
            // 成功后更新本地数据
            userInfo.value.avatar = avatarPath;
            userStore.userInfo = { ...userInfo.value };
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
            originalUserInfo.value = JSON.parse(JSON.stringify(userInfo.value));
            ElMessage.success('头像上传并更新成功');
          } else {
            ElMessage.error('头像路径保存失败: ' + (updateResponse?.message || '未知错误'));
          }
        } catch (error) {
          console.error('更新用户头像失败:', error);
          ElMessage.error('更新用户头像失败: ' + error);
        }
      } else {
        ElMessage.error(response?.message || '头像上传失败');
      }
    };
    
    const beforeAvatarUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isImage) {
        ElMessage.error('上传头像图片只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      return true;
    };
    
    const showPasswordDialog = () => {
      passwordForm.oldPassword = '';
      passwordForm.newPassword = '';
      passwordForm.confirmPassword = '';
      passwordDialogVisible.value = true;
    };
    
    const changePassword = async () => {
      if (!passwordFormRef.value) return;
      
      await passwordFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const response = await apiChangePassword({
              userId: userInfo.value.id,
              oldPassword: passwordForm.oldPassword,
              newPassword: passwordForm.newPassword
            });
            
            if (response.code === 200) {
              ElMessage.success('密码修改成功');
              passwordDialogVisible.value = false;
            } else {
              ElMessage.error(response.message || '密码修改失败');
            }
          } catch (error) {
            console.error('密码修改失败:', error);
            ElMessage.error('密码修改失败：' + (error.message || '未知错误'));
          }
        }
      });
    };
    
    return {
      userInfo,
      isEditing,
      defaultAvatar,
      userRoleText,
      passwordDialogVisible,
      passwordForm,
      passwordRules,
      passwordFormRef,
      startEditing,
      cancelEditing,
      saveProfile,
      handleAvatarSuccess,
      beforeAvatarUpload,
      showPasswordDialog,
      changePassword,
      avatarUrl
    };
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  width: 100%;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  display: flex;
  margin-top: 20px;
  gap: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.info-section {
  flex: 1;
}

.avatar-uploader {
  margin-top: 10px;
  text-align: center;
}
</style>
